$(function () {
    $('#book-add-form :radio.star').rating();
    $('#book-search-form :radio.star').rating();

    // AUTOCOMPLETE ROUTINES
    $("input#author").autocomplete({
        source: "autocomplete/authors",
        minLength: 2, //search after two characters
        select: function (event, ui) {
            $(this).val(ui.item.value);
            $(this).attr("auth_id", ui.item.id);
        }
    });

    $("input#publisher").autocomplete({
        source: "autocomplete/publishers",
        minLength: 2, //search after two characters
        select: function (event, ui) {
            $(this).val(ui.item.value);
            $(this).attr("pub_id", ui.item.id);
        }
    });

    $('#genre-tags').tagsInput({
        autocomplete_url: 'autocomplete/genres',
        minChars: 2,
        defaultText: 'Add a genre',
        removeWithBackspace: true,
        placeholderColor: '#666666',
        height: '19px',
        width: '98.5%'
    });

    $("input#author-search").autocomplete({
        source: "autocomplete/authors",
        minLength: 2, //search after two characters
        select: function (event, ui) {
            $(this).val(ui.item.value);
            $(this).attr("auth_id", ui.item.id);
        }
    });

    $("input#publisher-search").autocomplete({
        source: "autocomplete/publishers",
        minLength: 2, //search after two characters
        select: function (event, ui) {
            $(this).val(ui.item.value);
            $(this).attr("pub_id", ui.item.id);
        }
    });

    $('#genre-search').tagsInput({
        autocomplete_url: 'autocomplete/genres',
        minChars: 2,
        defaultText: 'Add a genre',
        removeWithBackspace: true,
        placeholderColor: '#666666',
        height: '19px',
        width: '98.5%'
    });
    //---------------------------------

    //---------COVER UPLOAD------------
    new AjaxUpload('#choose-cover', {
        action: 'books/upload_cover',
        name: 'myfile',

        onSubmit: function (file, ext) {
            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();
        },

        onComplete: function (file, response) {
            json_return = eval('(' + response + ')');

            if (json_return.response != 'success') {
                alert(json_return.value);
            } else {
                var height = parseInt($('td#tmp-cover').css('height'));
                $('img#show-cover').css('height', (height - 5) + 'px');
                $('img#show-cover').attr('src', '/assets/covers/' + json_return.value);
            }

            // enable upload button
            this.enable();

        }

    });
    //----------------------

    //Init datapicker
    $(function () {
        var dates = $("#datefrom, #dateto").datepicker({
            defaultDate: "+1w",
            changeMonth: true,
            numberOfMonths: 1,
            dateFormat: "dd/mm/yy",
            onSelect: function (selectedDate) {
                var option = this.id == "datefrom" ? "minDate" : "maxDate",
				instance = $(this).data("datepicker"),
				date = $.datepicker.parseDate(
					instance.settings.dateFormat ||
					$.datepicker._defaults.dateFormat,
					selectedDate, instance.settings);
                dates.not(this).datepicker("option", option, date);
            }
        });
    });
    //-------------------------------------------------

    //--------------Dialogs init--------------------
    $('div#book-add-edit-form').dialog({
        modal: true,
        autoOpen: false,
        width: 700,
        buttons: {
            "Confirm": function () {
                SaveBook();
                $(this).dialog("close");
            },
            "Cancel": function () {
                ResetForm();
                $(this).dialog("close");
            }
        }
    });

    $('div#book-search-form').dialog({
        modal: true,
        autoOpen: false,
        width: 700,
        height: 320,
        buttons: {
            "Find Books": function () {
                SearchBooks();
                $(this).dialog("close");
            },
            "Cancel": function () {
                ResetSearchForm();
                $(this).dialog("close");
            }
        }
    });

    $('div#book-reads-form').dialog({
        modal: true,
        autoOpen: false,
        width: 578,
        height: 300,
        buttons: {
            "Confirm": function () {
                SaveReads();            
                $(this).dialog("close");
            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });

    //---------------------------------------------------

    //-----------------------Dialog routines------------------------------
    function SaveReads() {
      $('tr.insert-read').each(function(){
        book_id = $(this).attr('book_id');
        kind = $(this).attr('kind');
        read_id = $(this).attr('read_id');
        
        status = $(this).find('select#status').val();
        start = $(this).find('input#datefrom').val();
        end = $(this).find('input#dateto').val();
        
        alert('book_id: '+book_id+' kind: '+kind+' read_id: '+read_id+' status: '+status+' start: '+start+' end: '+end);
      });
    }
    
    function SaveBook() {
        // Fade in the progress bar
        $('#book-add-edit-form #formProgress').hide();
        $('#book-add-edit-form #formProgress').html('<img src="/assets/images/ajax-loader.gif"/> Sending&hellip;');
        $('#book-add-edit-form #formProgress').fadeIn();

        // Disable the submit button
        $('#book-add-edit-form #submit').attr("disabled", "disabled");

        // Set temaprary variables for the script
        var isFocus = 0;
        var isError = 0;

        // Get the data from the form
        var id = $('#book-add-edit-form').attr('book_id');

        var title = $('#book-add-edit-form #title').val();
        var original = $('#book-add-edit-form #original-title').val();
        var author = $('#book-add-edit-form #author').attr('auth_id');
        var author_name = $('#book-add-edit-form #author').val();
        var publisher = $('#book-add-edit-form #publisher').attr('pub_id');
        var publisher_name = $('#book-add-edit-form #publisher').val();
        var genres = $('#book-add-edit-form #genre-tags').val();
        var pages = $('#book-add-edit-form #pages').val();
        var year = $('#book-add-edit-form #year').val();
        var buyed = $('#book-add-edit-form #buyed').val();
        var vote = 0;
        $('#book-add-form input.star').each(function () {
            if (this.checked) vote = this.value;
        });
        var description = $('#book-add-edit-form #description').val();
        var cover = $('img#show-cover').attr('src');

        // Validate the data
        if (title == '') {
            $('#book-add-edit-form #title').val('This is a required field.');
            $('#book-add-edit-form #title').focus();
            $('#book-add-edit-form #title').css("background", "red");

            isFocus = 1;
            isError = 1;
        }

        /*TODO: think on which data I need to add a validation*/

        // Terminate the script if an error is found
        if (isError == 1) {
            $('#book-add-edit-form #formProgress').html('');
            $('#book-add-edit-form #formProgress').hide();

            // Activate the submit button
            $('#book-add-edit-form #submit').attr("disabled", "");

            return false;
        }

        $.ajaxSetup({
            cache: false
        });

        var dataString = '';
        var load_url = '';
        var error_alert = '';

        if ($("div#book-add-edit-form").attr("edit") == 'true') {
            load_url = "books/edit_book";
            dataString = 'title=' + title + '&original=' + original + '&auth_id=' + author + '&pub_id=' + publisher + '&genres=' + genres + '&pages=' + pages + '&vote=' + vote + '&description=' + description + '&year=' + year + '&buyed=' + buyed + '&cover=' + cover + '&id=' + id + '&author=' + author_name + '&publisher=' + publisher_name;
            error_alert = 'There was an error editing the book. Please try again.';

        } else {
            load_url = "books/add_book";

            dataString = 'title=' + title + '&original=' + original + '&auth_id=' + author + '&pub_id=' + publisher + '&genres=' + genres + '&pages=' + pages + '&vote=' + vote + '&description=' + description + '&year=' + year + '&buyed=' + buyed + '&cover=' + cover + '&author=' + author_name + '&publisher=' + publisher_name;
            error_alert = 'There was an error adding the book. Please try again.';

        }

        $.ajax({
            type: "POST",
            url: load_url,
            data: dataString,
            success: function (msg) {
                // Activate the submit button
                $('#book-add-edit-form #submit').attr("disabled", "");

                $('div#body-container').html(msg);

                //return;
            },
            error: function (ob, errStr) {
                $('#book-add-edit-form #formProgress').html('');
                alert(error_alert);

                // Activate the submit button
                $('#book-add-edit-form #submit').attr("disabled", "");

                //return;
            }
        });

        $('#book-add-edit-form #formProgress').hide();

        return false;
    }

    function ResetForm() {
        $("div#book-add-edit-form").toggle(false);
        $("div#books-list").css({ "top": "45px" });

        $('#book-add-edit-form #formProgress').hide();

        $('li#search-button.button').removeAttr("disabled");

        $('#book-add-edit-form #title').val("");
        $('#book-add-edit-form #original-title').val("");
        $('#book-add-edit-form #author').val("");
        $('#book-add-edit-form #publisher').val("");
        $('#book-add-edit-form #genre-tags').importTags("");
        $('#book-add-edit-form #pages').val("");
        $('#book-add-edit-form #vote').val("");
        $('#book-add-edit-form #description').val("");
        $('input#year').val("");
        $('input#buyed').val("");

        var height = parseInt($('td#tmp-cover').css('height'));
        $('img#show-cover').css('height', (height - 5) + 'px');
        $('img#show-cover').attr('src', '/assets/covers/nocover.cvr');
    }

    function ResetSearchForm() {
        $('input#title-search').val("");
        $('input#author-search').val("");
        $('input#publisher-search').val("");
        $('input#genre-search').importTags("");
        $('input#pages-search').val("");
    }

    function SearchBooks() {
        $('#book-search-form #formProgress').hide();

        $('li#all-button.button').toggle(true);

        var title = $('#book-search-form #title-search').val();
        var title_where = $('select#title-where').val();
        var author = $('#book-search-form #author-search').val();
        var author_where = $('select#author-where').val();
        var publisher = $('#book-search-form #publisher-search').val();
        var publisher_where = $('select#publisher-where').val();
        var genres = $('#book-search-form #genre-search').val();
        var genres_where = $('select#genre-where').val();
        var pages = $('#book-search-form #pages-search').val();
        var pages_where = $('select#pages-where').val();
        var vote = 0;
        $('#book-search-form input.star').each(function () {
            if (this.checked) vote = this.value;
        });
        var vote_where = $('select#vote-where').val();

        var dataString = 'title=' + title + '&author=' + author + '&publisher=' + publisher + '&genres=' + genres + '&pages=' + pages + '&vote=' + vote +
						'&title_where=' + title_where + '&author_where=' + author_where + '&publisher_where=' + publisher_where +
						'&genres_where=' + genres_where + '&pages_where=' + pages_where + '&vote_where=' + vote_where;

        $.ajax({
            type: "POST",
            url: 'books/find_books',
            data: dataString,
            success: function (msg) {

                $('div#body-container').html(msg);

            },
            error: function (ob, errStr) {
                $('#book-search-form #formProgress').html('');
                alert('There have been errors searching the books!');

            }
        });

        ResetSearchForm();

        return false;

    }

});